package cn.edu.zhku.citrusmonitor.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
public class FileOperationUtil {

	/**
	 * @Titile:	上传文件
	 * @param request	http请求
	 * @param filePath	文件存放的相对路径
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, String[]> upload(HttpServletRequest request, String filePath) throws Exception {
		// 创建一个Map，用于存放表单数据
		Map<String, String[]> map = new HashMap<String, String[]>();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload sfu = new ServletFileUpload(factory);
		sfu.setHeaderEncoding("UTF-8");
		List<FileItem> fileItems = new ArrayList<FileItem>(0);
		// 解析request对象，并得到一个表单项的集合
		fileItems = sfu.parseRequest(request);
		// 遍历表单项集合数据
		for (FileItem fileItem : fileItems) {
			if (fileItem.isFormField()) {// 普通表单项
				String name = fileItem.getFieldName();// 得到字段名
				String value = fileItem.getString("UTF-8");// 得到字段值
				map.put(name, new String[] { value });
			} else { // 文件上传项
				File storeDirectory = new File(request.getServletContext().getRealPath(filePath)); 
				if (!storeDirectory.exists()) {
					storeDirectory.mkdirs(); // 创建目录
				}
				String fileName = fileItem.getName();
				if (fileName != null) {
					fileName = FilenameUtils.getName(fileName);// 保证不同浏览器得到的文件名都统一
				}
				fileName = System.currentTimeMillis() + "_" + fileName; // 防止同名文件覆盖
				// 目录打散
				String childDirectory = directoryBrokenByDate(storeDirectory, fileName);
				String absolutePath = storeDirectory + File.separator + childDirectory + File.separator + fileName;
				fileItem.write(new File(absolutePath));// 上传文件
				fileItem.delete();// 删除临时文件
				map.put(fileItem.getFieldName(), new String[] { filePath +"/"+ childDirectory + "/" + fileName});
			}
		}
		return map;
	}
	
	// 根据日期打乱文件
	public static String directoryBrokenByDate(File storeDirectory,String filename) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String dateDirectory = sdf.format(new Date());
		File file = new File(storeDirectory,dateDirectory);
		if(!file.exists()){
			file.mkdirs();
		}
		return dateDirectory;
	}
	
	// 根据哈希打乱文件
	public static String directoryBrokenByFile(File storeDirectory,String filename) {
		int hashCode = filename.hashCode();	
		String code = Integer.toHexString(hashCode);	
		String childDirectory = code.charAt(0)+File.separator+code.charAt(1);
		File file = new File(storeDirectory,childDirectory);
		if(!file.exists()){
			file.mkdirs();
		}
		return childDirectory;
	}

}
